window.sqlite3 = window.sqlite3 || {};
(function(ms,dbCfg) {
	
    ms.doSql = doSql;

    function doSql(cfg){
		var res = prepareArguments(cfg);
		if(!res.success) {
			cfg.fail(res);
			return ;
		}
		window.database.configure("busyTimeout", cfg.timeout)
		window.database[cfg.mode](cfg.sql,cfg.data,function(err,data){
                if (err) { 
                    cfg.fail(err);
					throw err; 
				}else{
                    cfg.success(data);
                  
                }
			});
    }
    
    function prepareArguments(cfg){
        if(!cfg)	return {"message" : "传入参数不能为空！",success : false};
        if(!cfg.sql) return {"message" : "必须传入sql ",success : false};
         
          cfg.timeout = cfg.timeout || 10000;// 10 seconds
          cfg.timeout = cfg.timeout <= 0 ?  10000 : cfg.timeout ;
 
         cfg.data = cfg.data || [];
         cfg.success = cfg.success || function(d){  };
         cfg.fail = cfg.fail || function(d){ alert(d.message);};
         
         return  {success : true}
	 }
	 //处理insert 语句
	 function prepareInsert(tableName,data){
		var cols = null;
        var vals = [];
        var ins = null;
        for (var prop in data){
            cols = (cols == null ? prop : cols+", "+prop);
            vals.push(data[prop]);
            ins = (ins == null ? "?" : ins+", "+"?");
        }
		var sql = "INSERT INTO "+tableName +"("+cols+") VALUES ("+ins+")";
		var o = {};
		o.sql = sql;
		o.v =  vals;
		return o;
       
	 }
	 //校验文件的正确性
	 ms.validataFile = function(filename,successCallback,failCallback,bfb){
		var db_bak =   new sqlite3.Database(filename, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
			function(err){
				if (err){
					console.log('FAIL on creating database ' + err);
					failCallback(err);
				}
			});
			db_bak.all("SELECT name FROM sqlite_master  WHERE type='table' ORDER BY name",function(err,data){
				if(err){
					console.log('导入数据失败 ' + err);
					db_bak.close();
					failCallback(err);
				}else{
					var total = data.length;
					var db = window.database;
					var complete = 1;
					db.serialize(function() {
						db.run('BEGIN TRANSACTION;');
						for(var i = 0 ; i < data.length ; i++){
							db.serialize(function(){
								//加载一个新的数据连接
						
							var tableName = data[i].name;
							if("t_sys_region" === tableName){
								return;
							}
							//var a =  
							db_bak.all("select * from " + tableName,function(err,d){
								//首先删除表
								//console.log(d);
								db.run("delete from "+ tableName,function(err,insertdata){
									if(err){
										console.log(tableName +"删除表出错");
										failCallback(err);
										return ;
									}
									
									//插入表
									//console.log(data.length);
									var a = 0;
									if(d.length == 0){
										complete++;
										//console.log("aaa="+a);
									}
									for(var t = 0 ; t < d.length;t++){
										var o = prepareInsert(tableName,d[t]);
										db.run(o.sql,o.v,function(){
											a++;
											bfb(tableName,a,d.length);
											if(a == d.length){
												//console.log(tableName);
												complete++;
												console.log(complete);
											}
											//console.log(tableName);
											if(complete === data.length){
												successCallback();
											}
										});
										
									//	console.log("dfdfdfdfdf");
									}
									
									// console.log("a="+a +"  d.length="+d.length + "  complete="+complete+" total-1="+(total-1));
									// if(complete === (total-1)){
									// 	console.log(tableName);
									// 	alert(123);
									// 	//successCallback();
									// 	// setTimeout(function () {
									// 	// 	successCallback();
									// 	//   }, 5000)
									// 	// ;
									// }
								
								});
								
							});
							});
						
						}

						db.run('COMMIT TRANSACTION;',function(err,res){
							if(err){
								failCallback(err);
							}else{
								
								if(successCallback){
									console.log("=====");
									console.log(db_bak);
									db_bak.close();
									//db.close(successCallback);
									//successCallback();
								}
							}
						});
						
						
					  });
					  //
					 
					//releaseConnection(db);
					
					
				}
			})
		

	 }

    //查询
    ms.selectBysql = function(sql,args,successCallback,failCallback){
		doSql({
             "mode":"all",
             "sql" : sql, 
			 "data" : args,
			 "success" : successCallback,
			 "fail" : failCallback
		});
	};
	//查询
	ms.all = function(sql, callback){
		window.database.configure("busyTimeout", 2000)
		window.database.all(sql,function(err,data){
				callback(err,data);
			});
	}
    ms.updateBysql = function(sql,args,successCallback,failCallback){
		doSql({
             "mode":"run",
             "sql" : sql, 
			 "data" : args,
			 "success" : successCallback,
			 "fail" : failCallback
		});
    };
    //更新或者删除
    /****
     * data {key:value}
     */
    ms.insertBysql = function(tableName,data,successCallback,failCallback){
        //需要处理 args
        // var cols = null;
        // var vals = [];
        // var ins = null;
        // for (var prop in data){
        //     cols = (cols == null ? prop : cols+", "+prop);
        //     vals.push(data[prop]);
        //     ins = (ins == null ? "?" : ins+", "+"?");
        // }
        // var sql = "INSERT INTO "+tableName +"("+cols+") VALUES ("+ins+")";
		// console.log('insert sql： ' + sql);
		var o = prepareInsert(tableName,data)
		ms.updateBysql(o.sql,o.v,successCallback,failCallback);
	};

	/****
	 * 
	 * 分页查询
	 */
	ms.pageBysql = function(cfg){ 
		prepareArguments(cfg);
		if(!cfg.page){
			cfg.fail({"message" : "分页参数不能为空！",success : false});
		}
		
		cfg.page.index = cfg.page.index || 1;
		cfg.page.index = cfg.page.index< 1 ? 1 : cfg.page.index; 
		
		cfg.page.size = cfg.page.size || 20;
		cfg.page.size = cfg.page.size  <1 ? 20 : cfg.page.size;
		
		
		var countSql = "select count(*) from ( "+cfg.sql+" ) aaaaa";
		var pageSql = cfg.sql +" LIMIT "+ ((cfg.page.index -1) * cfg.page.size) +","+ cfg.page.size;
		
		
		/* var jsonData = {
			"total": Math.ceil(allData().length / size),//总页数
			"page": page,//页码
			"records": allData().length,//总记录数
			"rows": allData().slice((page - 1) * size, page * size)//当前页的数据
		}; */
		var result = {
			"records" : 0,
			"page" : cfg.page.index,
			"total" : 0,
			"rows" : []
		};
		var conn = window.database;
		conn.configure("busyTimeout", 20000);
		conn.all(countSql,cfg.data, function (err, res, fs) {
			console.log(res);
			if (err) {
				 
				 cfg.fail(err); 
				 return ;
			}else{ 
				result.records = res[0]["count(*)"];
				result.total = Number.parseInt(result.records/cfg.page.size) + ( result.records % cfg.page.size ==0 ? 0 : 1);
				conn.all(pageSql,cfg.data, function (err, res, fs) {
					if (err) {
						
						 cfg.fail(err); 
						 return ;
					}else{
						result.rows = res;  
						
						cfg.success(result); 
					}
					
				});
				
				
			}
	}); 
		
	};
	/***
	 * 批量保存
	 * @argument tbl 表名
	 * @argument datas 数组对象
	 */
	ms.insertBatch = function(tbl,datas,successCallback,failCallback){
		var cdatas = datas ? datas.slice(0) : [];
		successCallback = successCallback || function(){};
		failCallback = failCallback || function(){};
		//处理sql语句
		
		var db = window.database;
		db.configure("busyTimeout", 20000);

		db.serialize(function(){
			db.run('BEGIN TRANSACTION;');
			for(var i = 0 ; i < datas.length;i++){
				var o = prepareInsert(tbl,datas[i]);
				console.log(o);
				db.run(o.sql,o.v);
			}
			db.run('COMMIT TRANSACTION;',function(err,res){
				if(err){
					failCallback(err);
				}else{
					successCallback(res);
				}
			});

		})
		
	
	}
	/***
	 * 批量处理
	 */
	ms.sqlBatch = function(sql,datas,successCallback,failCallback){
		//datas = datas || [];
		var cdatas = datas ? datas.slice(0) : [];
		successCallback = successCallback || function(){};
		failCallback = failCallback || function(){};
		//预编译sql语句
		var db = window.database;
		db.configure("busyTimeout", 20000);
		db.serialize(function(){
			db.run('BEGIN TRANSACTION;');
			for(var i = 0 ; i < cdatas.length;i++){
				db.run(sql,cdatas[i]);
			}
			db.run('COMMIT TRANSACTION;',function(err,res){
				if(err){
					failCallback(err);
				}else{
					successCallback(res);
				}
			});
		} )
		
		
	};
	ms.serializeSql = function(sqls,successCallback){
		var db = window.database;
		db.serialize(function() {
			// These two queries will run sequentially.
			db.run('BEGIN TRANSACTION;');
			var sql = sqls.split(";")
			for(var i = 0 ; i < sql.length ; i++){
				if(sql[i].trim()&& sql[i].trim() != "" && sql[i].trim() !=undefined){
					//同步执行
					db.run(sql[i].trim(),function(err){
						if(err){
							console.log(i)
							console.log(sql[i])
							console.log(err);
						}
					});
				}
				
			}
			db.run('COMMIT TRANSACTION;',function(err,res){
				if(err){
					//failCallback(err);
				}else{
					if(successCallback){
						successCallback();
					}
				}
			});
		
			
			
		  });
		 
	}
	
	ms.serialize = function(sqlFunction,successCallback,failCallback){
		var db = window.database;
		db.serialize(function() {
			// These two queries will run sequentially.
			db.run('BEGIN TRANSACTION;');
			sqlFunction(db);
			db.run('COMMIT TRANSACTION;',function(err,res){
				if(err){
					if(failCallback){
					  failCallback(err)
					}
				}else{
					if(successCallback){
						successCallback();
					}
				}
			});
			
			
			
		  });
		 
	}
})(window.sqlite3);

window.sqlite = window.sqlite3;
